#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
LastEditTime: 2024-08-27 14:27:30
Description: dock 配置管理界面

属性
    visible: bool, 是否默认显示
    name: str, 名称
    title: str, 标题
    desc: str, 描述
    dock: str, dock 位置

'''
"""config/sys/docks.json 示例
{
    "docks":[
        {
            "name":"toolbar",
            "desc":"替换菜单",
            "visible":true,
            "dock":"plugins.carvecloud.aircraft.dock"
        },
    ],
    "dockNestingEnabled":true,
    "noTitleBar":true
}
"""

__all__= []


import os
import gui.controls.globalvar as GL
import gui.controls.settings as ST
import gui.components.util_file as UFile
import gui.components.utils as utils
import gui.items.ribbonbar as RB

from PyQt5 import QtCore, QtGui, QtWidgets

# 插件配置文件位置
global CONFIG_FILE
CONFIG_FILE = "config/plugins/ribbonbars.json"
# ribbonbar 中各个widget区域使用对应的key进行记录，方便快速索引
global __KEY_WIDGETS
__KEY_WIDGETS = {}
# ribbonbar 中各个dock实例使用对应的key进行记录，方便快速索引
global __PLUGIN_INS
__PLUGIN_INS = {}

def init() -> None:
    """初始化docks
    """
    __init_config()
    RB.Ribbonbar._RIBBON = GL.get_value('ribbonbar')
    RB.Ribbonbar._KEY_WIDGETS = __KEY_WIDGETS
    __init_ribbonbars()
def __init_config() -> None:
    """初始化配置
    """
    ribbonbar = GL.get_value('ribbonbar')
    cfgIndex= ST.get_index_data() or {}
    if not __is_start(cfgIndex.get("ribbonbar")): return ribbonbar.hide()

    ribbonbarOptions = cfgIndex.get("ribbonbarOptions", {})
    ribbonHeight = ribbonbarOptions.get("ribbonHeight", 150) # 默认高度150  注意 插件中可能调用了 set_ribbon_height 更新此数值
    ribbonbar.setRibbonHeight(ribbonHeight)


    # 初始化 ribbonbar 区域变量
    __init_key_widgets()
    # 初始化默认的提示文本
    __init_module_text(ribbonbarOptions)
    # 设置首位置图标 一般为文件图标
    __init_file_icon(ribbonbarOptions)
    # 初始化快速访问区域
    __init_quick_widget(ribbonbarOptions)
    # 初始化右侧帮助访问区域
    __init_right_widget(ribbonbarOptions)
def __is_start(ribbonbar:bool=False) -> bool:
    """是否启用菜单栏
    Returns:
        bool: True 启用 False 不启用，默认不启用
    """
    return ribbonbar == True

def __init_key_widgets() -> None:
    """初始化 ribbonbar 区域索引，用于获取对应的 widget
    Args:
        无
    Returns:
        None
    """
    ribbonbar = GL.get_value('ribbonbar')
    _tabBarLayout = ribbonbar._titleWidget.layout()
    __set_widgets({
        "tabBarLayout": _tabBarLayout,
        # 快速访问按钮
        "quickAccessButtonsWidget": _tabBarLayout.itemAt(0).widget(),
        # 菜单栏
        "tabBarWidget":  _tabBarLayout.itemAt(1).widget(),
        # 中心标题栏
        "titleLableWidget": _tabBarLayout.itemAt(2).widget(),
        # 右侧帮助按钮组
        "rightButtonsWidget": _tabBarLayout.itemAt(3).widget()
    })
def __init_module_text(ribbonbarOptions:dict={}) -> None:
    """设置模块文本
    Args:
        ribbonbarOptions (dict, optional): 菜单栏配置. Defaults to {}.
    """
    moduleText = ribbonbarOptions.get("moduleText", "")
    if moduleText:
        ribbonbar = GL.get_value('ribbonbar')
        ribbonbar.setModuleText(moduleText)
def __init_file_icon(ribbonbarOptions:dict={}) -> None:
    """设置模块图标
    Args:
        ribbonbarOptions (dict, optional): 菜单栏配置. Defaults to {}.
    """
    fileIcon = ribbonbarOptions.get("fileIcon", None)
    if fileIcon:
        ribbonbar = GL.get_value('ribbonbar')
        ribbonbar.tabBar().setTabIcon(0,  QtGui.QIcon(fileIcon))
def __init_quick_widget(ribbonbarOptions:dict={}) -> None:
    """初始化快速访问区域
    Args:
        ribbonbarOptions (dict, optional): 菜单栏配置. Defaults to {}.
    Returns:
        None
    """
    quickAccessButtonsWidget = get_quick_bar_widget()
    hideQuickAccessWidgets  = ribbonbarOptions.get("hideQuickAccessWidgets", False)
    removeQuickAccessDefaultButtons  = ribbonbarOptions.get("removeQuickAccessDefaultButtons", False)
    if removeQuickAccessDefaultButtons:
        """移除默认的快速访问栏中的全部默认按钮"""
        layout = quickAccessButtonsWidget.layout()
        itemList = list(range(layout.count()))
        itemList.reverse()
        for i in itemList:
            item = layout.itemAt(i)
            layout.removeItem(item)
            widget = item.widget()
            if widget:
                widget.deleteLater()
    if hideQuickAccessWidgets:
        quickAccessButtonsWidget.setVisible(False)
def __init_right_widget(ribbonbarOptions:dict={}) -> None:
    """初始化右侧帮助访问区域
    Args:
        ribbonbarOptions (dict, optional): 菜单栏配置. Defaults to {}.
    Returns:
        None
    """
    rightButtonsWidget = get_right_bar_widget()
    hideRightDefaultButtons  = ribbonbarOptions.get("hideRightDefaultButtons", False)
    removeRightDefaultButtons  = ribbonbarOptions.get("removeRightDefaultButtons", False)
    if removeRightDefaultButtons:
        """移除默认的右侧帮助栏中的全部默认按钮"""
        layout = rightButtonsWidget.layout()
        itemList = list(range(layout.count()))
        itemList.reverse()
        for i in itemList:
            item = layout.itemAt(i)
            layout.removeItem(item)
            widget = item.widget()
            if widget:
                widget.deleteLater()
    if hideRightDefaultButtons:
        rightButtonsWidget.setVisible(False)
def __set_widgets(widgets:dict={}) -> None:
    """设置窗体
    Args:
        widgets (dict): ribbonbar 菜单中包含的窗体
    Returns:
        None
    """
    global __KEY_WIDGETS
    __KEY_WIDGETS = widgets
def __init_ribbonbars()-> None:
    """初始化菜单栏区域内容
    """
    mods = []
    # 构建 dock 实例
    for item in __init_items():
        importPath = item.get("import")
        try:
            moduleClasses = utils.get_all_subclasses(__import__(importPath, fromlist=[""]), RB.Ribbonbar)
            for module in moduleClasses:
                key = get_key(importPath, module)
                mod = module()
                add_key_ins(key, mod)
                mods.append(mod)
                # 装载
                mod.on_load()
        except Exception as e:
            print(e)
    # 初始化
    for mod in mods:
        mod.on_init()
def __init_items() -> list:
    """初始化dock items
    """
    items = []
    if os.path.exists(CONFIG_FILE):
        items = UFile.open_json(CONFIG_FILE) or []
    return items
def get_key(pos:str=None, module:RB.Ribbonbar=None) -> str:
    """获取实例key
    Args:
        name (str): 安装时生成的名字
        module (RB.Ribbonbar): 继承的类模块
    Returns:
        str: 返回组合的类名
    """
    return f"{pos}({module.__name__})"
def add_key_ins(name:str=None, ins:RB.Ribbonbar=None) -> None:
    """添加实例管理
    Args:
        name (str, optional): key索引. Defaults to None.
        pluginIns (ribbonbar.Ribbonbar, optional): 实例. Defaults to None.
    """
    global __PLUGIN_INS
    __PLUGIN_INS[name] = ins
def get_widget(name:str) -> QtWidgets.QWidget:
    """根据名称获取 ribbonbar 上的对应 widget
    Args:
        name (str): 窗体名称
    Returns:
        QtWidgets.QWidget: 窗体
    """
    return __KEY_WIDGETS.get(name)
def get_quick_bar_widget() -> QtWidgets.QWidget:
    """获取快捷 widget
    Returns:
        QtWidgets.QWidget: 窗体
    """
    return get_widget("quickAccessButtonsWidget")
def get_tab_bar_widget() -> QtWidgets.QWidget:
    """获取菜单 widget
    Returns:
        QtWidgets.QWidget: 窗体
    """
    return get_widget("tabBarWidget")
def get_title_bar_widget() -> QtWidgets.QWidget:
    """获取标题 widget
    Returns:
        QtWidgets.QWidget: 窗体
    """
    return get_widget("titleLableWidget")
def get_right_bar_widget() -> QtWidgets.QWidget:
    """获取右侧帮助栏 widget
    Returns:
        QtWidgets.QWidget: 窗体
    """
    return get_widget("rightButtonsWidget")

##  ============窗体测试程序 ================================
if  __name__ == "__main__":        ##用于当前窗体测试
    pass
